package cn.com.yang.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * UDP服务端
 * https://blog.csdn.net/cool_tao6/article/details/136553811
 * TODO
 * @author yangyijin
 * @since 2024年6月4日-上午11:35:04
 */
public class UdpEchoServer {
    private DatagramSocket socket = null;
    public UdpEchoServer(int port) throws SocketException {
        socket = new DatagramSocket(port);//参数里面指定端口号
    }
    //服务器的启动逻辑
    public void start() throws IOException {
        System.out.println("服务器启动");
        while (true) {
            //1、读取请求并解析
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(requestPacket);
            //把读到的字节数组，转换成字符串，方便后面的逻辑处理
            String request = new String(requestPacket.getData(), 0, requestPacket.getLength());
            //2、根据请求计算响应(对于回显服务器来说，这一步啥也不用做）
            String response =process(request);
            //3、把响应返回给客户端
            //构造一个 DatagramPacket 作为响应对象
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(), response.getBytes().length,
                    requestPacket.getSocketAddress());
            socket.send(responsePacket);
            //打印日志
            System.out.printf("[%s : %d] req: %s resp: %s", requestPacket.getAddress().toString(),
                    requestPacket.getPort(), request, response);
            System.out.println();
        }
    }
    //计算响应计算方法（这里没逻辑）
    public String process(String request) {
        return request;
    }
 
    public static void main(String[] args) throws IOException {
        UdpEchoServer udpEchoServer = new UdpEchoServer(9090);
        udpEchoServer.start();
    }
}
